package top.i51213.fastaction.action.image;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.pdf.PdfRenderer;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.net.Uri;
import android.util.Size;

import com.shockwave.pdfium.PdfDocument;
import com.shockwave.pdfium.PdfiumCore;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import top.i51213.fastaction.png.PngWriter;
import top.i51213.fastaction.uri.MimeType;
import top.i51213.fastaction.uri.UriReader;
import top.i51213.fastaction.uri.UriWriter;
import top.i51213.fastaction.util.IOUtil;

public class ImageCompressor {
    public static Size get(Context context) {
        try {
            CameraManager mCameraManager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
            for (final String cameraId : mCameraManager.getCameraIdList()) {
                CameraCharacteristics cameraCharacteristics = mCameraManager.getCameraCharacteristics(cameraId);
                StreamConfigurationMap streamConfigurationMap = cameraCharacteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
                Size[] sizes = streamConfigurationMap.getOutputSizes(ImageFormat.JPEG);
                for (Size size : sizes) {
                    System.out.println(size);
                }
                return sizes[0];
            }
        } catch (Exception ignored) {
        }
        return null;
    }

    public enum LimitRectSize {
        PX1200(1200 * 10000, "(超高清)"), PX800(800 * 10000, "(高清)"), PX400(400 * 10000, "");
        private final int value;
        private final String title;

        LimitRectSize(int value, String title) {
            this.value = value;
            this.title = title;
        }

        public int getValue() {
            return value;
        }

        public String getTitle() {
            return title;
        }
    }

    public static void compressJpeg(UriReader uriReader, UriWriter uriWriter, LimitRectSize limitRectSize, int limitStoreSize) throws IOException {
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        newOpts.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(uriReader.openAutoCloseInputStream(), null, newOpts);//此时返回bm为空
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        int sample = 1;
        while ((w / sample) * (h / sample) > limitRectSize.getValue()) {
            sample++;
        }
        newOpts.inJustDecodeBounds = false;
        newOpts.inSampleSize = sample;//设置缩放比例
        Bitmap bitmap = BitmapFactory.decodeStream(uriReader.openAutoCloseInputStream(), null, newOpts);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        for (int quality = 95; quality >= 15; quality -= 5) {
            baos.reset();
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
            //System.out.println("quality:" + quality + " store_size:" + baos.size()+" limit:"+limit);
            if (baos.size() < limitStoreSize) {
                break;
            }
        }
        bitmap.recycle();
        OutputStream outputStream = uriWriter.openOutputStream();
        baos.writeTo(outputStream);
        outputStream.close();
    }

    public static List<Uri> pdf2Jpeg(UriReader uriReader, LimitRectSize limitRectSize, int limitStoreSize) throws IOException {
        List<Uri> list = new ArrayList<>();
        Context context = uriReader.getContext();
        String displayName = IOUtil.getFileNameNoExt(uriReader.getDisPlayName(".pdf"));
        /*
        File cache=IOUtil.createCacheFile(context,displayName+IOUtil.getRandomTime()+".pdf");
        System.out.println(cache);
        MyPdfReader.openAndCopyTo(uriReader.openAutoCloseInputStream(),cache.getPath());
        PdfRenderer mPdfRenderer = new PdfRenderer(UriReader.fromFile(context,cache).openParcelFileDescriptor());
        */
        PdfRenderer mPdfRenderer = new PdfRenderer(uriReader.openParcelFileDescriptor());
        int count = mPdfRenderer.getPageCount();

        //System.out.println(displayName + " " + count);

        for (int index = 0; index < count; index++) {
            PdfRenderer.Page page = mPdfRenderer.openPage(index);
            int w = getD(page.getWidth(), limitRectSize);
            int h = getD(page.getHeight(), limitRectSize);
            Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
            //int p00=bitmap.getPixel(0,0);
            // bitmap.setHasAlpha(true);
            // System.out.println(Integer.toString(p00,16));
            page.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_PRINT);
            page.close();
            UriWriter uriWriter = new UriWriter(context, displayName + "_" + (index + 1) + ".jpg", MimeType.Image.Jpeg, true);
            OutputStream outputStream = uriWriter.openOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 80, outputStream);
            outputStream.close();
            bitmap.recycle();
            //System.out.println("add " + uriWriter.getUri());
            list.add(uriWriter.getUri());
        }
        mPdfRenderer.close();
        return list;
    }

    public static ArrayList<Uri> pdf2Jpeg2(UriReader uriReader, LimitRectSize limitRectSize) {
        ArrayList<Uri> list = new ArrayList<>();
        Context context = uriReader.getContext();
        String displayName = IOUtil.getFileNameNoExt(uriReader.getDisPlayName(".pdf"));
        PdfiumCore pdfiumCore = new PdfiumCore(context);
        try {
            PdfDocument pdfDocument = pdfiumCore.newDocument(uriReader.openParcelFileDescriptor());
            int count = pdfiumCore.getPageCount(pdfDocument);
            for (int index = 0; index < count; index++) {
                pdfiumCore.openPage(pdfDocument, index);
                int width = pdfiumCore.getPageWidthPoint(pdfDocument, index);
                int height = pdfiumCore.getPageHeightPoint(pdfDocument, index);
                int w = getD(width, limitRectSize);
                int h = getD(height, limitRectSize);
                Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
                pdfiumCore.renderPageBitmap(pdfDocument, bitmap, index, 0, 0, w, h);

                UriWriter uriWriter = new UriWriter(context, displayName + "_" + (index + 1) + ".jpg", MimeType.Image.Jpeg, true);
                OutputStream outputStream = uriWriter.openOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 80, outputStream);
                outputStream.close();
                bitmap.recycle();
                list.add(uriWriter.getUri());
            }
            pdfiumCore.closeDocument(pdfDocument); // important!
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        return list;
    }
    public static ArrayList<Uri> pdf2LongPng(UriReader uriReader, LimitRectSize limitRectSize) {
        ArrayList<Uri> list = new ArrayList<>();
        Context context = uriReader.getContext();
        String displayName = IOUtil.getFileNameNoExt(uriReader.getDisPlayName(".pdf"));
        PdfiumCore pdfiumCore = new PdfiumCore(context);
        try {
            PdfDocument pdfDocument = pdfiumCore.newDocument(uriReader.openParcelFileDescriptor());
            int count = pdfiumCore.getPageCount(pdfDocument);
            int th=0;
            int maxW=0;
            for (int index = 0; index < count; index++) {
                pdfiumCore.openPage(pdfDocument, index);
                int width = pdfiumCore.getPageWidthPoint(pdfDocument, index);
                int height = pdfiumCore.getPageHeightPoint(pdfDocument, index);
                int w = getD(width, limitRectSize);
                int h = getD(height, limitRectSize);
                th+=h;
                maxW=Math.max(w,maxW);
            }
            UriWriter uriWriter = new UriWriter(context, displayName+ ".png", MimeType.Image.Png, true);
            PngWriter pngWriter=new PngWriter(maxW,th,uriWriter.openOutputStream());
            for (int index = 0; index < count; index++) {
                pdfiumCore.openPage(pdfDocument, index);
                int width = pdfiumCore.getPageWidthPoint(pdfDocument, index);
                int height = pdfiumCore.getPageHeightPoint(pdfDocument, index);
                int w = getD(width, limitRectSize);
                int h = getD(height, limitRectSize);
                Bitmap bitmap = Bitmap.createBitmap(maxW, h, Bitmap.Config.ARGB_8888);
                pdfiumCore.renderPageBitmap(pdfDocument, bitmap, index, (maxW-w)/2, 0, w, h);
                pngWriter.addBitmap(bitmap);
                bitmap.recycle();
            }
            pngWriter.close();
            pdfiumCore.closeDocument(pdfDocument); // important!
            list.add(uriWriter.getUri());
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return list;
    }
    public static int getD(int src, LimitRectSize limitRectSize) {
        switch (limitRectSize) {
            case PX400:
                return src * 100 / 72;
            case PX800:
                return src * 200 / 72;
            case PX1200:
                return src * 300 / 72;
        }
        return src * 200 / 72;
    }
}
